package com.gjb6.customer.account.Login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Toast;

import com.gjb6.customer.BuildConfig;
import com.gjb6.customer.R;
import com.gjb6.customer.account.Account;
import com.gjb6.customer.account.AccountManager;
import com.gjb6.customer.account.ParamKey;
import com.gjb6.customer.account.UrlCenter;
import com.gjb6.customer.app.MainActivity;
import com.gjb6.customer.common.http.MyHttpRequest;
import com.gjb6.customer.common.http.TokenInfo;
import com.gjb6.customer.utils.FragmentUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.customviews.edittext.PasswordEditText;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.MD5Util;
import com.pachong.android.frameworkbase.utils.RegularUtils;
import com.pachong.android.frameworkbase.utils.SLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.itetPhone)
    EditText mItetPhone;

    public static boolean isForeground = false;
    public static final int TYPE = 3;
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static final String MESSAGE_RECEIVED_ACTION = "com.gjb6.customer.MESSAGE_RECEIVED_ACTION";
    private static boolean isExit = false;
    @Bind(R.id.itetPassword)
    PasswordEditText mItetPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AccountManager.getCurrentAccount() == null) {//未登录
            SLog.e("nullnullnull");
        } else {//已登录
// JPushInterface.setAlias(LoginActivity.this, AccountManager.getCurrentAccount().getId(), null);
            AccountManager.toRefreshToken(LoginActivity.this);//方法内部判断token是否该刷新，若需刷新，已刷新
            MainActivity.loginHuanxin(LoginActivity.this);
            MainActivity.start(this);
            finish();
        }

        initToolsBar();
        if (BuildConfig.DEBUG) {
            mItetPhone.setText("18359336832");
            mItetPhone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
            mItetPassword.setEditText("123456");
        }
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivity(intent);
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        context.startActivity(starter);
    }

    private void initToolsBar() {
        setTitle(R.string.login);
        getCustomToolbar().addRightButton(R.string.register, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.start(LoginActivity.this);
            }
        });
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_login, null);
    }

    private String getPhone() {
        return mItetPhone.getText().toString().trim();
    }

    private String getPassWord() {
        return mItetPassword.getEditText().trim().toString();
    }

    @OnClick({R.id.button, R.id.findPassWord})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button:
                login();
                break;
            case R.id.findPassWord:
                ForgetActivity.start(LoginActivity.this, TYPE);
                break;
        }
    }

    private void login() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWord())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isPassword(getPassWord())) {
            FragmentUtils.showWarnDialog("密码最多为6-20个字符", getSupportFragmentManager());
            return;
        }
        String enCodePwd = MD5Util.getMd5(getPassWord());//Md5加密
        setLoginRequest(getPhone(), enCodePwd);
    }

    private ProgressFragment progressFragment = new ProgressFragment();

    private void setLoginRequest(String phone, String password) {
        MyHttpRequest request = new MyHttpRequest(getBaseContext());
        JSONObject jobj = new JSONObject();
        try {
            jobj.put(ParamKey.LOGIN_NAME, phone);
            jobj.put(ParamKey.PASSWORD, password);
            if (!progressFragment.isVisible()) {
                progressFragment.show(getSupportFragmentManager());
            }
            request.post(UrlCenter.LOGIN, jobj, new DataRequestListener<TokenInfo>(TokenInfo.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(TokenInfo tokenInfo) {
                    Log.e("zf", "login onSuccess  bean == " + tokenInfo);
                    AccountManager.updateTokenInfo(tokenInfo);
                    JPushInterface.setAlias(LoginActivity.this, tokenInfo.getUser_id(), null);
                    setAccount(tokenInfo.getUser_id());
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(LoginActivity.this, strMsg);
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setAccount(String userId) {
        IHttpRequest request = new MyHttpRequest(this);
        request.get(UrlCenter.USER, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onSuccess(Account account) {
                account.setPhone(getPhone());
                account.setPassWord(MD5Util.getMd5("" + mItetPassword.getEditText().toString().trim()));
                AccountManager.setCurrentAccount(account);
                EasyToast.showToast(getBaseContext(), "登录成功");
                MainActivity.loginHuanxin(LoginActivity.this);
                MainActivity.start(LoginActivity.this);
                finish();
//                finish();
            }

            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
            }
        });
    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            } else {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);//退出程序
//                           finish();
            }
        }
        return false;
    }

}
